package com.gdk.ksoft.assembly.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.constants.GoodsTypeConstant;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.GoodsModuleTable;
import com.gdk.ksoft.data.entry.tables.GoodsTable;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.ui.works.models.FworkGoodsOrderModel;
import com.gdk.ksoft.assembly.utils.extensions.ControlUtils;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONObject;

import java.io.InputStream;
import java.util.HashMap;

/**
 * Created by hel on 2014-11-27.
 * 新增单品的Dialog
 */
public class NSingleProductDialog extends Dialog {

    public interface OnGoodsAddedListener{
        public void onGoodsAdded(int js, int ss, String goodsType);
    }

    @ViewInject(R.id.dialog_singleProduct_txtTitle)private TextView txtTitle;//标题文字
    @ViewInject(R.id.dialog_singleProduct_txtGoodsName)private TextView txtGoodsName;//商品名字
    @ViewInject(R.id.dialog_singleProduct_txtGoodsGg)private TextView txtGoodsGg;//商品规格
    @ViewInject(R.id.dialog_singleProduct_txtGoodsCode)private TextView txtGoodsCode;//商品条码
    @ViewInject(R.id.dialog_singleProduct_imgIcon)private ImageView imgGoodsIcon;//商品图标
    @ViewInject(R.id.dialog_singleProduct_txtGoodsStock)private TextView txtGoodsStock;//商品库存
    @ViewInject(R.id.dialog_singleProduct_etPiece)private EditText etPiece;//件数
    @ViewInject(R.id.dialog_singleProduct_etBottle)private EditText etBottle;//瓶数
    @ViewInject(R.id.dialog_singleProduct_etPiecePrice)private EditText etPiecePrice;//件价
    @ViewInject(R.id.dialog_singleProduct_txtPrice)private TextView txtPrice;//单价
    @ViewInject(R.id.dialog_singleProdct_txtMoney)private TextView txtMoney;//金额
    @ViewInject(R.id.dialog_singleProduct_txtSpecial)private TextView txtSpecial;//特殊选择
    @ViewInject(R.id.dialog_singleProdct_etSummary)private EditText etSummary;//说明文字
    @ViewInject(R.id.dialog_singleProduct_txtMinModule)private TextView txtMinModule;//小单位
    @ViewInject(R.id.dialog_singleProduct_txtMaxModule)private TextView txtMaxModule;//大单位

    private int netCustomerId = 0;//客户ID数据
    private int netAddressId = 0;//收货地址网络ID
    private int netGoodsId =0;//商品ID
    private int everyPieceNum = 0;//每件数量
    private String customerPriceName;//客户价格名称
    private FworkGoodsOrderModel model = null;//商品信息
    private View.OnFocusChangeListener flistener;
    private TextWatcher textWatcher;
    private OnGoodsAddedListener goodsAddedListener;
    private DbUtils dbUtils;//数据库操作对象

    public NSingleProductDialog(final Context context,Bundle data,OnGoodsAddedListener goodsAddedListener) {
        super(context,R.style.WindowDialogTheme);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View rootView = View.inflate(context, R.layout.dialog_nsingle_product,null);
        setContentView(rootView);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.horizontalMargin = 5f;
        getWindow().setAttributes(lp);
        ViewUtils.inject(this, rootView);
        initDialogInfo(context,data,goodsAddedListener);//初始化对话框数据
    }

    /**
     * 初始化对话框数据
     * @param context
     */
    public void initDialogInfo(final Context context,Bundle data,OnGoodsAddedListener goodsAddedListener){
        dbUtils = SQLiteUtils.getInstance(context).getDbUtils();
        model = new FworkGoodsOrderModel();
        this.goodsAddedListener = goodsAddedListener;//商品添加成功的数据监听器
        if(data!=null) {//获取页面传递的数据
            netCustomerId = data.getInt("netCustomerId");//获取客户网络ID
            netAddressId = data.getInt("netAddressId");//获取收货地址网络ID
            netGoodsId = data.getInt("netGoodsId");//获取商品网络ID
            customerPriceName = data.getString("priceName");//获取客户价格名称
            txtGoodsName.setText(data.getString("goodsName"));//获取商品规格
            txtGoodsGg.setText(data.getString("goodsGg"));//获取商品图片
            everyPieceNum = data.getInt("goodsPieceNum",0);//商品每件数量
            txtGoodsCode.setText(data.getString("goodsCode"));//获取商品条码
            txtMinModule.setText(data.getString("goodsMinMoudle"));//商品的最小计量单位
            new BitmapUtils(context).configDefaultLoadFailedImage(R.drawable.ic_default_goods)
                    .configDefaultLoadingImage(R.drawable.ic_default_goods)
                    .display(imgGoodsIcon, SystemData.BASE_URL + data.getString("goodsPic"));//获取商品图片
            model.kh_id = netCustomerId;//客户网络ID
            model.shdz_id = netAddressId;//客户送货地址网络ID
            registListenerForControls();//初始化界面操作
            initGoodsInfo(context);//初始化商品信息
        }
    }

    /**
     * 初始化商品信息
     */
    public void initGoodsInfo(final Context context){
        new AsyncTask<Void, Void, Void>() {
            private boolean isCanChangePrice = true;//是否能修改价格判断
            private ProgressDialog dialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    HashMap<String, Object> data = FworkDbHelper.queryPiecePrice(dbUtils, netGoodsId, customerPriceName);
                    model.goodsModuleInfo = (GoodsModuleTable) data.get("goodsModule");//获取商品计量单位
                    model.goodsInfo = (GoodsTable) data.get("goods");//获取商品数据
                    model.piecePrice = Float.parseFloat(data.get("piecePrice").toString());//获取件价
                    if(NetworkUtils.isNetAvailable(getContext())) {
                        HashMap<String, Object> priceInfo = requestGoodsPrice(netCustomerId, netAddressId, model.goodsInfo.id, model.goodsModuleInfo.hsgx);
                        if (priceInfo != null) {//通过访问网络获取的数据
                            model.piecePrice = Float.parseFloat(priceInfo.get("scfcj").toString());
                            model.isCanChangePrice = Integer.parseInt(priceInfo.get("xgbs").toString());
                            isCanChangePrice = model.isCanChangePrice == 1?true:false;//判断是否能修改价格
                            if(Float.compare(model.piecePrice,0.00f) == 0)//如果上次发出价得0，还是取本地价格
                                model.piecePrice = Float.parseFloat(data.get("piecePrice").toString());//获取件价
                            int kc = (int)Double.parseDouble(priceInfo.get("kc").toString());//获取库存信息
                            model.goodsInfo.kc = kc;//库存赋值，更新当前需要显示的库存信息
                            try{
                                //更新商品库存数据
                                dbUtils.execNonQuery("UPDATE shangpin SET kc = " + kc + " WHERE id = " + netGoodsId + ";");
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                            return null;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if (model.goodsModuleInfo != null && model.goodsInfo != null) {
                    if(!isCanChangePrice){//如果不能修改价格数据,冻结控件
                        etPiecePrice.setEnabled(false);
                        txtPrice.setEnabled(false);
                    }
                    model.goodsInfo.fcjj = model.piecePrice;//设置建议销售价
                    //txtGoodsGg.setText(txtGoodsGg.getText().toString()+(model.goodsInfo.mjsl+model.goodsInfo.dw));
                    txtMinModule.setText(model.goodsInfo.dw);
                    txtMaxModule.setText(model.goodsModuleInfo.jldwmc);
                    etPiecePrice.setText(FormatUtils.exactNumber(model.piecePrice, "0.00"));
                    txtPrice.setText("单价"+FormatUtils.exactNumber(model.piecePrice/model.goodsModuleInfo.hsgx,"0.00")+"元");
                    txtSpecial.setText(GoodsTypeConstant.GOODS_TYPE_TEXTS[0]);//设置选择类型的文字
                    float leftStock = model.goodsInfo.kc - model.goodsInfo.xl;
                    txtGoodsStock.setText("库存："+((int)leftStock/model.goodsModuleInfo.hsgx)+model.goodsModuleInfo.jldwmc
                            +((int)(leftStock%model.goodsModuleInfo.hsgx))+model.goodsInfo.dw);

                }else{
                    Toast.makeText(context,"加载商品信息失败!",Toast.LENGTH_SHORT).show();
                    NSingleProductDialog.this.dismiss();//关闭该窗口
                }
            }
        }.execute();
    }

    /**
     * 初始化界面操作
     */
    public void registListenerForControls(){
        flistener = new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                changeArguments();//没有焦点的时候计算
            }
        };
        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                changeArguments();//文本改变以后计算一次
            }
        };
        txtSpecial.setOnFocusChangeListener(flistener);
        etPiecePrice.setOnFocusChangeListener(flistener);
        etPiecePrice.addTextChangedListener(textWatcher);
        etPiece.setOnFocusChangeListener(flistener);
        etPiece.addTextChangedListener(textWatcher);
        etBottle.setOnFocusChangeListener(flistener);
        etBottle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if(!checkSingleNum()) return;//检测散数数据
                changeArguments();//文本改变以后计算一次
            }
        });
    }

    /**
     * 检测散数数据
     * @return
     */
    public boolean checkSingleNum(){
        if(!TextUtils.isEmpty(etBottle.getText().toString())) {
            String etBottleVal = ControlUtils.getNumberStringFromTextView(etBottle);
            String etPieceVal = ControlUtils.getNumberStringFromTextView(etPiece);
            int bottleNum = Integer.valueOf(etBottleVal);
            int pieceNum = Integer.valueOf(etPieceVal);
            if (everyPieceNum <= Math.abs(bottleNum)){
                Toast.makeText(getContext(),"散数数量不能超过规格规定!",Toast.LENGTH_SHORT).show();
                etBottle.setFocusable(true);
                return false;
            }
            if((bottleNum>=0 && pieceNum>=0) ||(bottleNum<=0 && pieceNum<=0))
                return true;
            else {
                Toast.makeText(getContext(),"件数或散数应有相同的符号!",Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    /**
     * 件价是否可用
     * @return
     */
    public boolean isPiecePriceAvaliable(){
        String price = ControlUtils.getNumberStringFromTextView(etPiecePrice);
        float minPrice = (float)SystemData.SaleManPower * model.goodsModuleInfo.dj;
        if(Float.compare(Float.parseFloat(price),0) == 0) return true;//价格为0时可用
        if(Float.compare(Float.parseFloat(price),minPrice )<0) {
            Toast.makeText(getContext(), "对不起，价格小于预期值"
                    + FormatUtils.exactNumber(minPrice,"0.00")+"元!", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 进行数据计算
     * @return
     */
    public void changeArguments(){
        String pieceNum = ControlUtils.getNumberStringFromTextView(etPiece);
        String bottleNum = ControlUtils.getNumberStringFromTextView(etBottle);
        String piecePrice = ControlUtils.getNumberStringFromTextView(etPiecePrice);//获得件价
        if(txtSpecial.getText().toString().trim().equals(GoodsTypeConstant.GOODS_TYPE_TEXTS[0])) {
            int pieceVal = Integer.valueOf(pieceNum);
            int bottleVal = Integer.valueOf(bottleNum);
            float finalprice = Float.valueOf(piecePrice);
            float money = pieceVal * finalprice + finalprice / model.goodsModuleInfo.hsgx * bottleVal;
            txtMoney.setText(FormatUtils.exactNumber(money, "0.00") + "元");
            txtPrice.setText("单价" + FormatUtils.exactNumber(finalprice/model.goodsModuleInfo.hsgx, "0.00")+"元");
        }else{
            txtMoney.setText("0.00元");
        }
    }

    @OnClick(value={R.id.dialog_singleProduct_txtSpecial,R.id.dialog_singleProduct_txtCancel,
            R.id.dialog_singleProduct_txtOK,R.id.dialog_singleProduct_txtPrice})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.dialog_singleProduct_txtSpecial://类型选择
                showGoodsTypeDialog();//显示商品类型选择框
                break;
            case R.id.dialog_singleProduct_txtCancel://放弃
                this.dismiss();
                break;
            case R.id.dialog_singleProduct_txtOK://确认添加单品
                float finalPrice = Float.parseFloat(ControlUtils.getNumberStringFromTextView(etPiecePrice));
//                if(Float.compare(finalPrice,0.00f) == 0){
//                    Toast.makeText(getContext(),"请确认当前单价是否可用!",Toast.LENGTH_SHORT).show();
//                    return;
//                }
                addGoodsOrderInformation();//添加一条订单商品信息
                break;
            case R.id.dialog_singleProduct_txtPrice://修改单价
                showSinglePriceDialog();//显示单价提示框
                break;
        }
    }

    /**
     * 显示商品类型选择框
     */
    public void showGoodsTypeDialog(){
        new AlertDialog.Builder(getContext()).setItems(GoodsTypeConstant.GOODS_TYPE_SIMPLE_TEXTS,new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                txtSpecial.setText(GoodsTypeConstant.GOODS_TYPE_SIMPLE_TEXTS[which]);
                model.goodsType = GoodsTypeConstant.GOODS_TYPE_SIMPLE_VALUES[which];
                if(which!=0){
                    txtMoney.setText("0.00元");
                }else{
                    changeArguments();
                }
            }
        }).show();
    }


    /** 显示单价提示框 **/
    public void showSinglePriceDialog(){
        double realPrice = model.goodsModuleInfo.dj/model.goodsModuleInfo.hsgx;//原单价
        double minPrice = Double.compare(SystemData.SaleManPower,0) == 0?realPrice:realPrice*SystemData.SaleManPower;//最小价格
        new FixPriceDialog(getContext(),realPrice,minPrice,new FixPriceDialog.OnPriceChangedListener() {
            @Override
            public void onPriceChange(double price) {
                txtPrice.setText("单价"+FormatUtils.exactNumber(price,"0.00")+"元");
                etPiecePrice.setText(FormatUtils.exactNumber(price*model.goodsModuleInfo.hsgx,"0.00"));
            }
        }).show();
    }

    /** 添加一条订单商品信息 **/
    public void addGoodsOrderInformation(){
        String pieceNum = ControlUtils.getNumberStringFromTextView(etPiece);
        String bottleNum = ControlUtils.getNumberStringFromTextView(etBottle);
        String piecePrice = ControlUtils.getNumberStringFromTextView(etPiecePrice);
        model.pieceNum = Integer.valueOf(pieceNum);
        model.singleNum = Integer.valueOf(bottleNum);
        model.noteInfomation = etSummary.getText().toString();//获取备注信息
        model.finalPrice = Float.valueOf(piecePrice);
        model.totalMoney = !txtSpecial.getText().toString().equals("正常")?0:(model.pieceNum*model.finalPrice
                + model.singleNum*model.finalPrice/model.goodsModuleInfo.hsgx);
        if((pieceNum.equals("0") && bottleNum.equals("0"))){
            Toast.makeText(getContext(),"请输入商品正确的数量值!",Toast.LENGTH_SHORT).show();
            return;
        }
        if(!checkSingleNum()) return;//检测散数数据
        if(!isPiecePriceAvaliable()) return;//检查价格数据
        try {
            if(model.pieceNum*model.goodsModuleInfo.hsgx+model.singleNum>model.goodsInfo.kc-model.goodsInfo.xl
                    && SystemData.IsGoodsStockNotice == 1){//提示库存标识为1时提醒
                if(SystemData.saleMan.xdkcqx == 0){
                    Toast.makeText(getContext(),"当前库存量小于购买数量，不能添加商品!",Toast.LENGTH_SHORT).show();
                    return;
                }
                changeGoodsInfo();//存储商品信息
//                showOutofStockDialog();//显示超出库存的提示框
                return;
            }
            changeGoodsInfo();//存储商品信息
        }catch(Exception e){
            e.printStackTrace();
            Toast.makeText(getContext(),"添加订单商品失败!",Toast.LENGTH_SHORT).show();
        }
    }

    /** 存储商品信息 **/
    public void changeGoodsInfo()throws Exception{
        new AsyncTask<Void,Void,Void>(){
            private String errMessage;
            private ProgressDialog dialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(getContext(),"","正在提交数据...");
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    FworkDbHelper.saveShoppingCartGoods(dbUtils, model);
//                    dbUtils.update(model.goodsModuleInfo,WhereBuilder.b("sp_id", "=", model.goodsInfo.id), "dj");
                }catch (Exception e){
                    errMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    Toast.makeText(getContext(), "添加订单商品失败!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(goodsAddedListener!=null) //输出商品的件数和散数以及商品类型
                    goodsAddedListener.onGoodsAdded(model.pieceNum,model.singleNum,txtSpecial.getText().toString());
                Toast.makeText(getContext(), "添加订单商品成功!", Toast.LENGTH_SHORT).show();
                NSingleProductDialog.this.dismiss();
            }
        }.execute();
    }

    /**
     * 请求商品价格
     * @param khid 客户ID
     * @param dzid 收货地址ID
     * @param goodsid 商品ID
     * @param hsgx  商品换算关系
     */
    public static HashMap<String,Object> requestGoodsPrice(int khid,int dzid,int goodsid,int hsgx){
        try {
            RequestParams params = new RequestParams("UTF-8");
            String methodName = "Cx_GetSpJg";
            String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"kh_id\":" + khid + ",\"shdz_id\":" + dzid + ",\"sp_id\":" + goodsid + ",\"hsgx\":" + hsgx + "}}";
            System.out.println("-----> 获取商品价格数据：" + messageBody);
            params.addBodyParameter("Method", methodName);
            params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
            params.addBodyParameter("MessageBody", messageBody);
            InputStream is = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT/3)
                    .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT/2)
                    .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
            String result = FileUtils.stream2string(is, "UTF-8");
            System.out.println("------->获取商品价格的结果是："+result);
            if (!TextUtils.isEmpty(result)) {
                BaseResultModel resultModel = new Gson().fromJson(result,BaseResultModel.class);
                if(resultModel!=null && resultModel.Result.equals("0000")) {
                    HashMap<String, Object> value = new HashMap<>();
                    JSONObject jobj = new JSONObject(resultModel.Data);
                    if(jobj.has("scfcj")) value.put("scfcj",jobj.getDouble("scfcj"));
                    if(jobj.has("xgbs")) value.put("xgbs",jobj.getInt("xgbs"));
                    if(jobj.has("kc")) value.put("kc",jobj.getDouble("kc"));
                    return value;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("------>获取商品价格失败："+e.getMessage());
        }
        return null;
    }

}
